<template>
  <div>
    <el-upload
      class="avatar-uploader"
      :action="UPLOAD_URL"
      :show-file-list="false"
      :on-success="handleUploadSuccess"
    >
      <el-image
        v-if="localImageUrl !== ''"
        :src="cdn_url(localImageUrl)"
        style="width: 200px; height: 200px"
        fit="cover"
      />
      <el-icon v-else class="avatar-uploader-icon">
        <Plus />
      </el-icon>
    </el-upload>
  </div>
</template>

<script lang="ts" setup>
import { Plus } from "@element-plus/icons-vue";
import { UPLOAD_URL } from "@/constants/BaseConstants";
import { ref, watch } from "vue";
import { cdn_url } from "@/utils/common";

defineOptions({
  name: "单个图片上传"
});

const props = defineProps({
  value: {
    type: String
  }
});

// 创建本地副本
const localImageUrl = ref(props.value);
// 监听 props 的变化，更新本地副本
watch(
  () => props.value,
  newValue => {
    localImageUrl.value = newValue;
  }
);

function handleUploadSuccess(response: any) {
  localImageUrl.value = response.url;
  emits("updateImageUrl-event", localImageUrl.value);
}

const emits = defineEmits(["updateImageUrl-event"]);
</script>

<style scoped>
.avatar-uploader .avatar {
  display: block;
  width: 178px;
  height: 178px;
}
</style>

<style>
.avatar-uploader .el-upload {
  position: relative;
  overflow: hidden;
  cursor: pointer;
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  width: 178px;
  height: 178px;
  font-size: 28px;
  color: #8c939d;
  text-align: center;
}
</style>
